<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class weixin extends Controller
{
    //
    private function checkSignature()
    {
        $signature = $_GET["signature"];//获取GET请求中的参数"signature"
        $timestamp = $_GET["timestamp"];//获取GET请求中的参数"timestamp"
        $nonce = $_GET["nonce"];        //获取GET请求中的参数"nonce"

        $token = TOKEN;//将代码中我们定义的TOKEN赋值给token
        $tmpArr = array($token, $timestamp, $nonce);//将以上三个参数放进数组
        sort($tmpArr, SORT_STRING);//将数组的元素当做字符串来处理，并按升序排序
        $tmpStr = implode( $tmpArr );//将排序好的数组元素重新组合成一个字符串
        $tmpStr = sha1( $tmpStr );//进行sha1加密

        if( $tmpStr == $signature ){//将组合的字符串和微信服务器传过来的参数"signature"进行对比
            return true;
        }else{
            return false;
        }
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;//校验成功，返回随机字符串
            exit;
        }
    }
}
